package auctionhaus

import grails.converters.JSON

class ListingService {
    def jmsService
    def mailService

    def addListing(String name, String description, Date endTime, Customer seller, double startBid) {
        def listingInstance = new Listing(
                name: name,
                description: description,
                endTime: endTime,
                seller: seller,
                startBid: startBid
        )
        listingInstance.save(flush: true)
        return listingInstance
    }

    def postCompletedListings() {
        def incompleteListings = Listing.findAll {
            isComplete == false
        }
        incompleteListings.each {
            if(it.endTime < new Date()) {
                println it.name
                it.isComplete = true
                if(it.bids) {
                    it.winner = (it.bids.sort {it.dateCreated}.reverse())[0].bidder
                    notifyWinner(it)
                }
                //send email here
                it.save(flush: true)
                def message = it as JSON
                jmsService.send(queue: 'completedListingsQueue', message.toString(true))
            }
        }
    }

    def notifyWinner(Listing listing) {
        mailService.sendMail {
            to listing.winner.email
            from "auctionhaustest@gmail.com"
            subject "Winning bid placed on listing " + listing.name
            body "You have placed the winning bid for listing " + listing.name
        }
    }
}
